﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Json;
using CM = System.Configuration.ConfigurationManager;

namespace Teein.Proxy.Bot.Helper
{
    /// <summary>
    /// 文本处理类
    /// </summary>
    public class TextHelper
    {
        #region 获取webconfig当中appSetting中的配置项
        /// <summary>
        /// 获取webconfig当中appSetting中的配置项
        /// </summary>
        /// <param name="key">配置项的键</param>
        /// <returns>配置项的值</returns>
        public static string GetConfigItem(string key)
        {
            string result = string.Empty;
            try
            {
                result = CM.AppSettings[key];
            }
            catch { }
            return result;
        }
        #endregion

        #region 对指定的字符串,进行md5加密散列值计算
        /// <summary>
        /// 对指定的字符串,进行md5加密散列值计算
        /// </summary>
        /// <param name="source">需要md5加密的字符串值</param>
        /// <returns>md5值</returns>
        public static string MD5(string source)
        {
            byte[] result = Encoding.Default.GetBytes(source);
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            return ByteArrayToHexString(md5.ComputeHash(result));
        }
        #endregion

        #region 把对应的字节值转换为对应的字符串
        /// <summary>
        /// 把对应的字节值转换为对应的字符串
        /// </summary>
        /// <param name="values">字节值</param>
        /// <returns>字符串</returns>
        private static string ByteArrayToHexString(byte[] values)
        {
            StringBuilder sb = new StringBuilder();
            foreach (byte value in values)
            {
                sb.AppendFormat("{0:X2}", value);
            }
            return sb.ToString();
        }
        #endregion

        /// <summary>
        /// 将字符串转换为JSON对象集合
        /// </summary>
        /// <param name="jsonString">JSON字符串</param>
        /// <returns>JSON对象集合</returns>
        public static JsonObjectCollection JsonParse(string jsonString)
        {
            JsonTextParser jtp = new JsonTextParser();
            JsonObjectCollection joc;
            try
            {
                joc = jtp.Parse(jsonString) as JsonObjectCollection;
            }
            catch
            {
                joc = new JsonObjectCollection();
            }

            return joc;
        }

        /// <summary>
        /// 从JSON字符串中获取对应的属性
        /// </summary>
        /// <param name="jsonString">JSON字符串</param>
        /// <param name="name">属性名称</param>
        /// <returns>JSON字符串中获取对应的属性</returns>
        public static string GetValueByName(string jsonString, string name)
        {
            string result = string.Empty;

            JsonTextParser jtp = new JsonTextParser();

            JsonObjectCollection joc = jtp.Parse(jsonString) as JsonObjectCollection;

            foreach (JsonObject jo in joc)
            {
                if (jo.Name == name)
                {
                    var joctemp = (jo as JsonObjectCollection);
                    var jocarrtemp = (jo as JsonArrayCollection);
                    if (joctemp == null && jocarrtemp == null)
                    {
                        result = Convert.ToString(jo.GetValue());
                    }
                    else
                    {
                        result = jo.ToString();
                    }
                    break;
                }
                else
                {
                    JsonObjectCollection temp = (jo as JsonObjectCollection);

                    if (temp != null && temp.Count > 0)
                    {
                        result = GetValueByName(temp, name);

                        if (!string.IsNullOrEmpty(result))
                        {
                            break;
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 从JSON对象集合当中获取对应的属性
        /// </summary>
        /// <param name="joc">JSON对象集合</param>
        /// <param name="name">属性名称</param>
        /// <returns>JSON对象集合当中获取对应的属性</returns>
        public static string GetValueByName(JsonObjectCollection joc, string name)
        {
            string result = string.Empty;

            foreach (JsonObject jo in joc)
            {
                if (jo.Name == name)
                {
                    var joctemp = (jo as JsonObjectCollection);
                    var jocarrtemp = (jo as JsonArrayCollection);
                    if (joctemp == null && jocarrtemp == null)
                    {
                        result = Convert.ToString(jo.GetValue());
                    }
                    else
                    {
                        result = jo.ToString();
                    }
                    break;
                }
                else
                {
                    JsonObjectCollection temp = (jo as JsonObjectCollection);

                    if (temp != null && temp.Count > 0)
                    {
                        result = GetValueByName(temp, name);

                        if (!string.IsNullOrEmpty(result))
                        {
                            break;
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 将字符串转换为JSON对象数组
        /// </summary>
        /// <param name="jsonText">JSON字符串</param>
        /// <returns>JSON对象数组</returns>
        public static JsonArrayCollection JsonParseToArrayCollection(string jsonText)
        {
            if (!string.IsNullOrEmpty(jsonText))
            {
                return (new JsonTextParser().Parse(jsonText) as JsonArrayCollection);
            }
            else
            {
                return new JsonArrayCollection();
            }
        }

        /// <summary>
        /// 将字符串转换为JSON对象集合
        /// </summary>
        /// <param name="jsonText">JSON字符串</param>
        /// <returns>JSON对象集合</returns>
        public static JsonObjectCollection JsonParseToObjectCollection(string jsonText)
        {
            if (jsonText.Contains("[]"))
            {
                jsonText = jsonText.Replace("[]", "\"\"");
            }
            if (jsonText.Contains("[ ]"))
            {
                jsonText = jsonText.Replace("[ ]", "\"\"");
            }
            if (jsonText.Contains("{}"))
            {
                jsonText = jsonText.Replace("{}", "\"\"");
            }
            if (!string.IsNullOrEmpty(jsonText))
            {
                try
                {
                    return (new JsonTextParser().Parse(jsonText) as JsonObjectCollection);
                }
                catch
                {
                    return new JsonObjectCollection();
                }
            }
            else
            {
                return new JsonObjectCollection();
            }
        }

        #region 字符串转成 column in ('','','','',)的条件字符串
        /// <summary>
        ///  字符串转成 column in ('','','','',)的条件字符串
        /// </summary>
        /// <param name="strings">字符串</param>
        /// <param name="split">拆分字符</param>
        /// <returns></returns>
        public static string ConvertStringArrayToWhere(string strings, string split)
        {
            string[] array = strings.Split(split.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            return ConvertStringArrayToWhere(array);
        }

        /// <summary>
        /// 组合数组为('','','','',)的条件字符串
        /// </summary>
        /// <param name="array">数组</param>
        /// <returns>query的条件</returns>
        public static string ConvertStringArrayToWhere(string[] array)
        {
            //组合guid为query的条件
            StringBuilder where = new StringBuilder();
            where.Append("('");
            where.Append(string.Join("','", array));
            where.Append("')");

            return where.ToString();
        }

        /// <summary>
        /// 组合数组为('','','','',)的条件字符串
        /// </summary>
        /// <param name="array">数组</param>
        /// <returns>query的条件</returns>
        public static string ConvertStringArrayToWhere(IEnumerable<string> array)
        {
            return ConvertStringArrayToWhere(array.ToArray());
        }

        /// <summary>
        /// 组合数组为('','','','',)的条件字符串
        /// </summary>
        /// <param name="array">数组</param>
        /// <returns>query的条件</returns>
        public static string ConvertIntArrayToWhere(IEnumerable<int> array)
        {
            //组合guid为query的条件
            StringBuilder where = new StringBuilder();
            where.Append("('");
            where.Append(string.Join("','", array));
            where.Append("')");

            return where.ToString();
        }
        #endregion

        #region 转化为PinYin匹配的条件
        /// <summary>
        /// 查询关键字
        /// </summary>
        /// <param name="searchTxt"></param>
        /// <returns></returns>
        public static string ConvertStringToPinYinWhereString(string searchTxt)
        {
            StringBuilder where = new StringBuilder();
           
            if (!string.IsNullOrEmpty(searchTxt))
            {
                char[] chararray = searchTxt.ToCharArray();
                
                where.Append("%");
                where.Append(string.Join("%", chararray));
                where.Append("%");
            }

            return where.ToString();
        }
        #endregion

        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="encode">加密采用的编码方式</param>
        /// <param name="source">待加密的明文</param>
        /// <returns></returns>
        public static string EncodeBase64(Encoding encode, string source)
        {
            byte[] bytes = encode.GetBytes(source);
            string encodeString = "";
            try
            {
                encodeString = Convert.ToBase64String(bytes);
            }
            catch
            {
                encodeString = source;
            }
            return encodeString;
        }

        /// <summary>
        /// Base64加密，采用utf8编码方式加密
        /// </summary>
        /// <param name="source">待加密的明文</param>
        /// <returns>加密后的字符串</returns>
        public static string EncodeBase64(string source)
        {
            return EncodeBase64(Encoding.UTF8, source);
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="encode">解密采用的编码方式，注意和加密时采用的方式一致</param>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(Encoding encode, string result)
        {
            string decodeString = "";
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decodeString = encode.GetString(bytes);
            }
            catch
            {
                decodeString = result;
            }
            return decodeString;
        }

        /// <summary>
        /// Base64解密，采用utf8编码方式解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(string result)
        {
            return DecodeBase64(Encoding.UTF8, result);
        }
    }
}
